package com.retail.bbq.cola.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.retail.bbq.cola.service.TencentAdCallbackService;
import com.retail.bbq.cola.vo.request.TencentAdCallbackRequest;
import com.retail.bbq.cola.vo.response.TencentAdCallbackResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Slf4j
@Service
public class TencentAdCallbackServiceImpl implements TencentAdCallbackService {

    @Resource
    private RestTemplate restTemplate;

    private static final String TENCENT_API_URL = "https://api.e.qq.com/v1.3/user_actions/add";
    private static final String ACCESS_TOKEN = "a0415b9afe626ce1b30347d1b6a50e61";
    private static final String ACCOUNT_ID = "26095129";
    private static final String USER_ACTION_SET_ID = "1202983609";
    private static final String ACTION_TYPE = "REGISTER";
    //  腾讯广告数据回传的接口文档地址
    //  https://datanexus.qq.com/doc/develop/guider/interface/action/dmp_actions_add
    @Override
    public TencentAdCallbackResponse callback(TencentAdCallbackRequest request) {
        TencentAdCallbackResponse response = new TencentAdCallbackResponse();

        try {
            // 构建请求参数
            Map<String, Object> requestBody = buildRequestBody(request);

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Access-Token", ACCESS_TOKEN);
            long currentTimeMillis = System.currentTimeMillis();
            headers.set("timestamp", String.valueOf(currentTimeMillis / 1000));
            headers.set("nonce", generateNonce(currentTimeMillis));

            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

            log.info("调用腾讯广告API，请求参数：{}", JSONObject.toJSONString(requestBody));

            // 发送请求
            ResponseEntity<Map> apiResponse = restTemplate.exchange(
                    TENCENT_API_URL,
                    HttpMethod.POST,
                    entity,
                    Map.class
            );

            log.info("腾讯广告API响应：{}", JSONObject.toJSONString(apiResponse.getBody()));

            // 处理响应
            Map<String, Object> responseBody = apiResponse.getBody();
            if (responseBody != null) {
                response.setSuccess(true);
                response.setCode((Integer) responseBody.get("code"));
                response.setMessage((String) responseBody.get("message"));
                response.setData(responseBody.get("data"));
            } else {
                response.setSuccess(false);
                response.setMessage("接口返回空响应");
            }

        } catch (Exception e) {
            log.error("调用腾讯广告API失败", e);
            response.setSuccess(false);
            response.setMessage("调用腾讯广告API失败: " + e.getMessage());
        }

        return response;
    }

    /**
     * 构建腾讯广告API请求参数
     */
    private Map<String, Object> buildRequestBody(TencentAdCallbackRequest request) {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("account_id", ACCOUNT_ID);
        requestBody.put("user_action_set_id", USER_ACTION_SET_ID);

        // 构建actions数组
        Map<String, Object> action = new HashMap<>();
        action.put("action_type", ACTION_TYPE);

        // 设置时间戳，如果请求中没有则使用当前时间
        long actionTime = System.currentTimeMillis() / 1000;
        action.put("action_time", actionTime);

        // 设置用户标识，优先使用click_id
        Map<String, String> trace = new HashMap<>();
        trace.put("click_id", request.getClickId());
        action.put("trace", trace);
        requestBody.put("actions", new Object[]{action});
        return requestBody;
    }

    /**
     * 生成nonce随机字符串
     * 前半部分为当前时间戳(毫秒)，后面随机生成数字+字母随机数补齐32位
     * @param timestamp 时间戳(毫秒)
     * @return 32位随机字符串
     */
    private String generateNonce(long timestamp) {
        String timestampStr = String.valueOf(timestamp);
        int remainingLength = 32 - timestampStr.length();
        
        if (remainingLength <= 0) {
            // 如果时间戳已经超过32位，截取前32位
            return timestampStr.substring(0, 32);
        }
        
        // 生成随机字符串补齐
        String chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random random = new Random();
        StringBuilder randomStr = new StringBuilder();
        
        for (int i = 0; i < remainingLength; i++) {
            randomStr.append(chars.charAt(random.nextInt(chars.length())));
        }
        
        return timestampStr + randomStr.toString();
    }

}